package order;

import enums.TrialType;
import models.BaseModel;
import models.merchant.Merchant;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/6.
 * 订单投诉表
 */
@Entity
@Table(name = "report")
public class Report extends BaseModel {
    /**
     * 订单ID
     */
    @JoinColumn(name = "order_id", nullable = true)
    @ManyToOne
    public Order order;

    /**
     * 订单明细ID
     */
    @JoinColumn(name = "order_item_id", nullable = true)
    @ManyToOne
    public OrderItem orderItem;

    /**
     * 所属商户
     */
    @JoinColumn(name = "merchant_id", nullable = true)
    @ManyToOne
    public Merchant merchant;

    /**
     * 购买数量
     */
    @Column(name = "buy_number")
    public Integer buyNumber;

    /**
     * 销售单价
     */
    @Column(name = "sale_price")
    public Double salePrice;

    /**
     * 总金额 = 销售单价*购买数量
     */
    @Column(name = "amount")
    public Double amount;

    /**
     * 胜诉类型
     */
    @Column(name = "trial")
    @Enumerated(EnumType.STRING)
    public TrialType trial;


    /**
     * 商户是否填写过备注
     */
    @Transient
    public String trialStr;


    /**
     * 商户查询 被投诉订单
     * @param
     * @return
     */
    public static Report getReportById(long id) {
        return Report.find(" id = ?", id).first();
    }

    /**
     * 商户查询 被投诉订单
     * @param merchant
     * @return
     */
    public static List<Report> getListByMerchant(Merchant merchant) {
        return Report.find(" merchant.id = ?  and trial = null", merchant.id).fetch();
    }

    public static JPAExtPaginator<Report> findByCondition(Map<String, Object> conditionMap, String orderByExpress, Integer pageNumber, Integer pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder(" ").append("/~  t.order.orderNumber = {orderNumber} ~/");
          /*      .append("/~ and t.order.createdAt >= STR_TO_DATE({startTime},'%Y-%m-%d %H:%i:%s') ~/")
                .append("/~ and t.order.createdAt <= STR_TO_DATE({endTime},'%Y-%m-%d %H:%i:%s') ~/");*/
        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        Logger.info("sql : %s" , result.getXsql());
        JPAExtPaginator<Report> reportPage = new JPAExtPaginator<>("Report t", "t", Report.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        if(pageNumber != null && pageSize != null) {
            reportPage.setPageNumber(pageNumber);
            reportPage.setPageSize(pageSize);
        }
        reportPage.setBoundaryControlsEnabled(false);
        return reportPage;
    }

}
